import requests
from datetime import datetime, timedelta

# 只能维护服务器端响应的cookie js生成的cookie通过逆向解决(逆向会讲)
# headers = {
#     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
# }
# session = requests.Session()
# # session = requests.session()
# url = 'https://xueqiu.com/'
# # 获取访问首页时响应的cookie
#
# # session.get(url, headers=headers)
# # 统一设置headers
# session.headers = headers
# response = session.get(url)
#
# if response.status_code == 200:
#     print("登录成功")
#     # 解析 Set-Cookie 响应头
#     cookies = response.cookies
#     for cookie in cookies:
#         expires = cookie.expires
#         if expires:
#             cookie_expiry_time = datetime.fromtimestamp(expires)
#             print(f"Cookie 过期时间: {cookie_expiry_time}")
# else:
#     print("登录失败")
#
# url = 'https://xueqiu.com/statuses/hot/listV2.json?since_id=-1&max_id=596226&size=15'
# # 手动携带cookie进行访问
# # res = session.get(url, headers=headers)
# res = session.get(url)
# print(res.content.decode())
#
#
# #
# # 创建一个 session 对象
# session = requests.Session()

headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
    }
session = requests.Session()
def login(session):

    # session = requests.session()
    url = 'https://xueqiu.com/'
    # 获取访问首页时响应的cookie

    # session.get(url, headers=headers)
    # 统一设置headers
    session.headers = headers
    response = session.get(url)

    if response.status_code == 200:
        print("登录成功")
        # 解析 Set-Cookie 响应头
        cookies = response.cookies
        for cookie in cookies:
            expires = cookie.expires
            if expires:
                cookie_expiry_time = datetime.fromtimestamp(expires)
                print(f"Cookie 过期时间: {cookie_expiry_time}")
        return True
    else:
        print("登录失败")
        return False


def is_cookie_expired(session):
    for cookie in session.cookies:
        if cookie.expires:
            expiry_time = datetime.fromtimestamp(cookie.expires)
            if datetime.now() >= expiry_time:
                return True
    return False


# 初次登录获取 cookie
if login(session):
    # 获取当前时间
    last_login_time = datetime.now()
    print(f"上次登录时间: {last_login_time}")

    # 检查 cookie 是否过期
    if is_cookie_expired(session):
        print("Cookie 已过期，重新登录...")
        login(session)
    else:
        print("Cookie 仍然有效")

    # 定期更新 cookie，每天更新一次
    while True:
        current_time = datetime.now()
        if current_time >= last_login_time + timedelta(days=1):
            print("每天更新一次 cookie...")
            if login(session):
                last_login_time = current_time
else:
    print("无法初次登录获取 cookie")
